import {getToken, setToken, removeToken} from 'utils/auth'
import {setStore, getStore} from 'utils/store'
import {encryption, deepClone} from 'utils/util'
import crud from 'utils/crud'
import website from '@/config/website';
import {Base64} from 'js-base64'
// import router from "../../router";
// import reloadRoutes from '@/router/avue-router'
import menuApi from "@/api/menuApi";

const user = {
    state: {
        userInfo: {},
        permission: {},
        roles: [],
        menuId: {},
        menu: getStore({name: 'menu'}) || [],
        menuAll: getStore({name: 'menuAll'}) || [],
        isMenuDataLoaded: false,
        token: getStore({name: website.Authorization}) || '',
        refreshToken: getStore({name: website.Authorization}) || '',
    },
    actions: {
        /**
         * 根据用户名+密码登录
         * @param commit
         * @param userInfo
         * @returns {Promise<unknown>}
         * @constructor
         */
        LoginByUsername({commit}, userInfo = {}) {
            return new Promise((resolve) => {
                let data = {
                    "channel": "ACCOUNT_OR_PHONE_PASSWORD",
                    "captchaId": userInfo.captchaId,
                    "data": {
                        "username": userInfo.username,
                        "password": Base64.encode(userInfo.password)
                    }
                }
                crud.post("/api/admin/sys/login", data).then(res => {
                    commit('SET_TOKEN', res.headers[website.Authorization]);
                    commit('DEL_ALL_TAG', []);
                    commit('CLEAR_LOCK');
                    resolve(res);
                });
            })
        },
        /**
         * 根据手机号登录
         * @param commit
         * @param userInfo
         * @returns {Promise<unknown>}
         * @constructor
         */
        LoginByPhone({commit}, userInfo) {
            return new Promise((resolve) => {
                let menuAll = state.menuAll
                // loginByUsername(userInfo.phone, userInfo.code).then(res => {
                //     const data = res.data.data;
                //     commit('SET_TOKEN', data);
                //     commit('DEL_ALL_TAG', []);
                //     commit('CLEAR_LOCK');
                //     resolve();
                // })
            })
        },
        /**
         * 获取当前的登录人用户信息
         * @param commit
         * @returns {Promise<unknown>}
         * @constructor
         */
        GetUserInfo({commit}) {
            return new Promise((resolve, reject) => {
                crud.get("/api/admin/sys/loginUser/findUser").then(res => {
                    const data = res.data.data;
                    commit('SET_USER_INFO', data);
                    commit('SET_ROLES', data.roles);
                    resolve(res);
                });
            })
        },
        /**
         * 登出
         * @param commit
         * @returns {Promise<unknown>}
         * @constructor
         */
        LogOut({commit}) {
            return new Promise((resolve) => {
                let token = getToken();
                if (token) {
                    // 后端登出
                    crud.post("/api/admin/sys/login/loginOut").then(res => {
                        commit('SET_USER_INFO', {});
                        commit('SET_TOKEN', '');
                        commit('SET_MENU_ALL', []);
                        commit('SET_MENU', []);
                        commit('SET_ROLES', []);
                        commit('DEL_ALL_TAG', []);
                        commit('CLEAR_LOCK');
                        // 前端登出
                        removeToken();
                        resolve()
                    });
                } else {
                    commit('SET_USER_INFO', {});
                    commit('SET_TOKEN', '');
                    commit('SET_MENU_ALL', []);
                    commit('SET_MENU', []);
                    commit('SET_ROLES', []);
                    commit('DEL_ALL_TAG', []);
                    commit('CLEAR_LOCK');
                    // 前端登出
                    removeToken();
                    getStore({name: 'tag'}).label = "登录"
                    resolve()
                }
            })
        },
        /**
         * 注销session
         * @param commit
         * @returns {Promise<unknown>}
         * @constructor
         */
        FedLogOut({commit}) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '');
                commit('SET_MENU', []);
                commit('SET_TAG_LIST', []);
                commit('SET_ROLES', []);
                commit('DEL_ALL_TAG', []);
                commit('CLEAR_LOCK');
                removeToken();
                resolve()
            })
        },
        /**
         * 获取顶部菜单
         */
        GetTopMenu() {
            return new Promise(async resolve => {
                let menus = await menuApi.getMenus(true);
                menus.forEach(item => item.menus = null)
                resolve(menus)
            })
        },
        /**
         * 获取系统菜单
         * @param commit
         * @param item 点击的那条数据,顶部菜单数据
         */
        GetMenu({commit}, item) {
            return new Promise(async resolve => {
                let menus = await menuApi.getMenus();
                let newMenus = deepClone(menus);
                // 获取左菜单 (通过pid, 默认索引0的)
                let leftMenus = newMenus[0].menus;
                if (item != null && item.id) {
                    for (let i = 0; i < newMenus.length; i++) {
                        if (newMenus[i].id === item.id) {
                            leftMenus = newMenus[i].menus;
                        }
                    }
                }
                // commit('SET_MENU_ALL', newMenus);
                commit('SET_MENU', leftMenus);
                commit('SET_IS_MENU_DATA_LOADED', true);
                // 重新加载路由, 让菜单发生变化后点击顶部菜单更新数据后可实时生效
                // await reloadRoutes(router,menus)
                resolve(leftMenus)
            })
        },
    },
    mutations: {
        SET_TOKEN: (state, token) => {
            setToken(token);
            state.token = token;
        },
        SET_MENU_ID(state, menuId) {
            state.menuId = menuId;
        },
        SET_IS_MENU_DATA_LOADED(state, isMenuDataLoaded) {
            state.isMenuDataLoaded = isMenuDataLoaded;
        },
        SET_USER_INFO: (state, userInfo) => {
            state.userInfo = userInfo;
            setStore({name: 'userInfo', content: userInfo})
        },
        SET_MENU_ALL: (state, menuAll) => {
            setStore({name: 'menuAll', content: menuAll})
        },
        SET_MENU: (state, menu) => {
            state.menu = menu;
            setStore({name: 'menu', content: state.menu})
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles;
        },
    }
}
export default user